﻿
using FreeSql;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Msung.Core;
using Msung.Core.Caching;
using Msung.Core.Model;
using Quartz;
using System;
using System.Diagnostics;

namespace IcIntegration.Job.Jobs
{
    public class ExecuteSqlServiceJob : IJob
    {
        private readonly ILogger _logger;
        private readonly IServiceProvider _serviceProvider;
        private bool read = false;

        public ExecuteSqlServiceJob(
            IServiceProvider serviceProvider,
            ILogger<ExecuteSqlServiceJob> logger)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            if (!read)
            {
                Task.Factory.StartNew(() =>
                {
                    ExecuteSql();
                });
            }
        }

        public void ExecuteSql()
        {
            JobOption? jobOption = AppSetting.JobOptions.FirstOrDefault(m => m.Key == this.GetType().Name);
            string? redisKey = jobOption?.RedisKey;
            int sqlQty = jobOption == null ? 5 : jobOption.Qty;

            string strSql = "";
            try
            {
                read = true;
                using (var scope = _serviceProvider.CreateScope())
                {
                    var _redisRepository = scope.ServiceProvider.GetRequiredService<IRedisOperationRepository>();
                    var _freeSqlCloud = scope.ServiceProvider.GetRequiredService<FreeSqlCloud<string>>();
                    var _freesql = _freeSqlCloud.Change("TRACER");

                    while (read)
                    {
                        var listCount = _redisRepository.ListLength("ExecuteSqlList");
                        if (listCount == 0)
                        {
                            read = false;
                            return;
                        }

                        strSql = _redisRepository.ListRightPop("ExecuteSqlList");
                        Task.Factory.StartNew(() =>
                        {
                            try
                            {
                                _logger.LogDebug($"PROCESS:{Process.GetCurrentProcess().Id};SESSION:{Process.GetCurrentProcess().SessionId};开始执行SQL语句:{DateTime.Now.ToString("yyyy-MM-dd HH24:mi:ss")}");
                                _freesql.Ado.ExecuteNonQuery(strSql);
                                _logger.LogDebug($"PROCESS:{Process.GetCurrentProcess().Id};SESSION:{Process.GetCurrentProcess().SessionId};结束执行SQL语句:{DateTime.Now.ToString("yyyy-MM-dd HH24:mi:ss")}");
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError($"定时执行SQL语句服务异常\r\n" + ex.Message);
                                _redisRepository.ListLeftPush("SqlErrorList", strSql);
                            }
                        });
                        Thread.Sleep(500);
                    }
                }
            }
            catch (Exception ex)
            {
                read = false;
                _logger.LogError(ex.Message);
            }
        }
    }
}

